package com.jinyang.jetpackdemo.hilt

import androidx.hilt.Assisted
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/8/25
 * @Description:
 */
//@ActivityRetainedScoped
//class MyViewModel @Inject constructor(private val repository: Repository): ViewModel() {
//    var result: MutableLiveData<String> = MutableLiveData()
//    fun doWork() {
//        viewModelScope.launch {
//            runCatching {
//                withContext(Dispatchers.IO){
//                    repository.getData()
//                }
//            }.onSuccess {
//                result.value="RepoResponse=${Gson().toJson(it)}"
//            }.onFailure {
//                result.value=it.message
//            }
//        }
//    }
//}

class MyViewModel @ViewModelInject constructor(
    private val repository: Repository,
    //SavedStateHandle 用于进程被终止时，保存和恢复数据
    @Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
    var result: MutableLiveData<String> = MutableLiveData()
    private val userId: MutableLiveData<String> = savedStateHandle.getLiveData("userId")

    fun doWork() {
        viewModelScope.launch {
            runCatching {
                withContext(Dispatchers.IO) {
                    repository.getData(userId)
                }
            }.onSuccess {
                result.value = "RepoResponse=${Gson().toJson(it)}"
            }.onFailure {
                result.value = it.message
            }
        }
    }
}
